package org.example.study11.condition;
// 生产者消费者模型（有界缓冲区）
public class ProducerConsumerTest {
    public static void main(String[] args) {
        BoundedBuffer<Integer> buffer = new BoundedBuffer<>(3); // 创建容量为3的缓冲区

        // 创建生产者线程
        Thread producer1 = new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    buffer.put(i);          // 生产数字1-5
                    Thread.sleep(100);      // 模拟生产过程
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "生产者-1");

        Thread producer2 = new Thread(() -> {
            try {
                for (int i = 6; i <= 10; i++) {
                    buffer.put(i);          // 生产数字6-10
                    Thread.sleep(150);      // 模拟生产过程
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "生产者-2");

        // 创建消费者线程
        Thread consumer1 = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    buffer.take();          // 消费5次
                    Thread.sleep(200);      // 模拟消费过程
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "消费者-1");

        Thread consumer2 = new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    buffer.take();          // 消费5次
                    Thread.sleep(250);      // 模拟消费过程
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, "消费者-2");

        // 启动所有线程
        consumer1.start();                  // 启动消费者1
        consumer2.start();                  // 启动消费者2
        producer1.start();                  // 启动生产者1
        producer2.start();                  // 启动生产者2
    }
}